<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { IconMinusCircleFill } from '@arco-design/web-vue/es/icon';
import mainkey from '@/assets/images/mainkey_img.svg';
import zone from '@/assets/images/zone_img.svg';
import { TABLE_COLUMNS } from '@/constants/dataManage';
import API from '@/services';
import { Message } from '@arco-design/web-vue';
const props = defineProps<{ updateTable: string }>();
type IOptions = {
  label: string;
  value: string;
};
const drawerTableData = reactive<any[]>([]);
const showTableTips = ref<boolean>(false);
let tableFieldOption = reactive<any>({
  data: []
});

// 如果先选择分区则数据类型只能为DATE,否则分区只能禁用;如果有date类型选择了分区则其他字段不能选分区
const handleChooseFieldType = (row: any, index: any, data: any) => {
  if (row.tableFieldType != 'DATE') {
    row.ifPartition = false;
  } else {
    let datetimeLen = drawerTableData.filter((item: any) => {
      return !!item?.ifPartition;
    });
    if (datetimeLen?.length) {
      row.disabled = true;
    }
  }
};
const handleChoosePart = (val: any, row: any) => {
  const getDateTime = drawerTableData.filter(
    (item) => item.tableFieldType === 'DATE'
  );
  if (val) {
    row.ifPrimaryKey = true;
    getDateTime?.forEach((item: any) => {
      item.disabled = true;
    });
    row.disabled = false;
  } else {
    row.ifPrimaryKey = false;
    getDateTime?.forEach((item: any) => {
      item.disabled = false;
    });
  }
};

// 获取表字段类型列表
const getTableFieldList = async () => {
  try {
    const { data, code } = await API.enumBao.getGetTableColumnType();
    if (code === 200) {
      data?.map((item: any) => {
        if (item.value === 'INT' || item.value === 'DATE') {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
        return {
          ...item
        };
      });
      tableFieldOption.data = data;
    }
  } catch (error) {}
};
// 添加字段
const handleAddField = () => {
  const addTableList = {
    key: drawerTableData.length + 1,
    index: drawerTableData.length + 1,
    tableFieldName: '',
    tableFieldType: '',
    tableFieldDesc: ''
  };
  drawerTableData.push(addTableList);
  showTableTips.value = false;
};
// 删除当前列表
const handleDeleteRow = (index: any, rows: any) => {
  rows.splice(index, 1);
};

const addTableRef = ref();
// 不允许有相同的字段名，取出相同的字段名称
const exposeFn = () => {
  if (drawerTableData?.length) {
    const hasFieldName = drawerTableData.map((value) =>
      value.tableFieldName.trim()
    );
    const reg = /^[a-zA-Z][A-Za-z0-9_]*$/;
    if (hasFieldName.includes('')) {
      Message.warning('字段名未填写');
      return false;
    }
    let validBoolean = hasFieldName.filter((item: any) => !reg.test(item));
    if (validBoolean?.length) {
      Message.warning('字段名只能输入以字母开头的字母、数字和_');
      return;
    }

    const hasFieldType = drawerTableData.filter(
      (item: any) => !item.tableFieldType
    );

    if (hasFieldType?.length) {
      Message.warning('请选择数据类型');
      return false;
    }

    const DuplicateData = new Set(hasFieldName);
    if ([...DuplicateData].length != hasFieldName.length) {
      Message.warning('字段名重复');
      return false;
    }
    const hasMainKeyField = drawerTableData?.filter(
      (item) => item?.ifPrimaryKey
    );
    if (!hasMainKeyField?.length && props.updateTable === 'buildTable') {
      Message.warning('必须要有字段勾选主键');
      return false;
    }

    if (props.updateTable === 'buildTable') {
      let datetimeLen = drawerTableData.filter((item: any) => {
        return item.tableFieldType === 'DATE' && !!item?.ifPartition;
      });
      if (datetimeLen?.length >= 2) {
        Message.warning('为DATE类型数据的字段只能有一个分区');
        return false;
      }
    }

    return addTableRef.value;
  } else {
    showTableTips.value = true;
    return false;
  }
};
onMounted(() => {
  getTableFieldList();
});
defineExpose({ exposeFn });
</script>

<template>
  <div v-show="showTableTips" class="col_red table-tips">请添加字段</div>
  <div class="add-feild-btn">
    <a-button type="primary" @click="handleAddField">+添加字段</a-button>
  </div>
  <a-table
    class="add-table-field"
    :columns="TABLE_COLUMNS"
    :data="drawerTableData"
    :pagination="false"
    ref="addTableRef"
    style="margin-top: 20px"
  >
    <template #index="{ record, rowIndex }">
      <span>{{ rowIndex + 1 }}</span>
    </template>
    <template #tableFieldName="{ record, rowIndex }">
      <a-input v-model="record.tableFieldName" />
    </template>
    <template #tableFieldType="{ record, rowIndex }">
      <a-select
        v-model="record.tableFieldType"
        @change="handleChooseFieldType(record, rowIndex, drawerTableData)"
      >
        <a-option
          v-for="item of tableFieldOption.data"
          :label="item.label"
          :value="item.value"
          :disabled="!!record.ifPartition && item.disabled"
          >{{ item.label }}</a-option
        >
      </a-select>
    </template>
    <template #tableFieldDesc="{ record, rowIndex }">
      <a-input v-model="record.tableFieldDesc" />
    </template>
    <template #operator="{ record, rowIndex }">
      <a-space size="small">
        <a-checkbox
          :disabled="record.ifPartition"
          v-model="record.ifPrimaryKey"
        >
          <a-tooltip content="主键">
            <img class="va_m" :src="mainkey" alt="" />
          </a-tooltip>
        </a-checkbox>
        <a-checkbox
          v-model="record.ifPartition"
          @change="handleChoosePart($event, record)"
          :disabled="
            props.updateTable === 'updateTable' ||
            record.tableFieldType != 'DATE' ||
            record.tableFieldType === '' ||
            record.disabled
          "
        >
          <a-tooltip content="分区">
            <img class="va_m" :src="zone" alt="" />
          </a-tooltip>
        </a-checkbox>
        <icon-minus-circle-fill
          @click="handleDeleteRow(rowIndex, drawerTableData)"
          class="fill-svg"
        />
      </a-space>
    </template>
  </a-table>
</template>

<style lang="scss">
.add-feild-btn {
  margin-top: -36px;
  float: right;
}
.add-table-field {
  margin-left: -80px;
}
.fill-svg > path {
  fill: red;
}
.table-tips {
  float: left;
  margin-left: -64px;
}
</style>
